<?php
import("ORG.Util.Function");
import("@.Org.CommonTool");
import("@.Org.FunctionTool");
import("@.Org.GoodsTool");
import("@.Org.Utils");

class GoodsAction extends CommonAction{	
	// 变量
	private $return	=	array(
		'content'	=>null,
		'error'		=>0,
		'message'	=>''
	);
	
	public function _initialize(){
		parent::_initialize();				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	
	public function _empty(){
		t('空操作');
	}
	
	// 商品列表
	public function goods_list(){

	    $cat_id 		= 	empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
	    $code   		= 	empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
	    $suppliers_id 	= 	isset($_REQUEST['suppliers_id']) ? (empty($_REQUEST['suppliers_id']) ? '' : trim($_REQUEST['suppliers_id'])) : '';
	    $is_on_sale 	= 	isset($_REQUEST['is_on_sale']) ? ((empty($_REQUEST['is_on_sale']) && $_REQUEST['is_on_sale'] === 0) ? '' : trim($_REQUEST['is_on_sale'])) : '';
		$is_delete		=	isset($_REQUEST['is_delete']) ? ((empty($_REQUEST['is_delete']) && $_REQUEST['is_delete'] === 0) ? 0 : trim($_REQUEST['is_delete'])) : 0;
	    $real_goods		=	$code == '' ? 1 : 0; 	// 1: 代表真实商品;0:代表虚拟商品
		
	    $this->assign('is_on_sale', $is_on_sale);
	    $this->assign('suppliers_id', $suppliers_id);	    
	    $this->assign('code', $code);	    
	    
	    $GoodsCatModel	=	new GoodsCatModel();	    
	    /* 供货商 */
	    $supplierList		=	M('Suppliers')->field("suppliers_id, suppliers_name, suppliers_desc")->where("is_check = 1")->select();	    	    
	    $this->assign('supplierList', $supplierList); 
	    /* 商品分类 */
	    $goodsCatList		=	$GoodsCatModel->cat_list();
	    $this->assign('goodsCatList', $goodsCatList); 
	    /* 品牌列表 */
	    $brandList			=	GoodsCatModel::get_brand_list();	    
	    $this->assign('brandList', $brandList);
	    /* 推荐 */
	    $this->assign('introTypeList', Utils::get_intro_list());
	    /* 商品列表 */ 
	    $sql_goods_list			=	Utils::sql_goods_list($is_delete, $real_goods);
	    
	    //t($sql_goods_list);
	    
	    /*$this->assign('filter',$goods_list['filter']);	 // 过滤条件*/
	    $param = array(
				'result'	=> $sql_goods_list,					//分页用的数组或sql
				'listvar'	=> 'goodsList',		//分页循环变量
				'listRows'	=> 15,					//每页记录数
				'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'	=> 'content',	    	//ajax更新内容的容器id，不带#
				'pagesId'	=> 'page',				//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'	=> 'Goods:l_goods_list',//ajax更新模板
		);
		$this->goods_page($param);
		$this->display();
	}
	
	/**
	 +----------------------------------------------------------
	 * 分页函数 支持sql和数据集分页 sql请用 buildSelectSql()函数生成
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param array  $result 排好序的数据集或者查询的sql语句
	 * @param int    $totalRows  每页显示记录数 默认21
	 * @param string $listvar    赋给模板遍历的变量名 默认list
	 * @param string $parameter  分页跳转的参数
	 * @param string $target  分页后点链接显示的内容id名
	 * @param string $pagesId  分页后点链接元素外层id名
	 * @param string $template ajaxlist的模板名
	 * @param string $url ajax分页自定义的url
	 +----------------------------------------------------------
	 */
	public function goods_page($param) {
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template 	= 	(!$template) ? 'ajaxlist' : $template;
			//exit($this->fetch($template));
			$this->ajaxReturn(1, $this->fetch($template), 1);
		}
		return $voList;
	}
	
	// 添加商品
	public function add_goods(){
		// 商品分类	
		$GoodsCatModel	=	new GoodsCatModel();
		$goodsCatList	=	$GoodsCatModel->getCategoryList();
		// 品牌
		//$brandList		=	M('Brand')->field("brand_id,brand_name")->select();
		$this->assign("goodsCatList",		$goodsCatList);
		$this->assign("brand_list",			get_brand_list());
		$this->assign('user_rank_list', 	get_user_rank_list());
		$this->assign('member_price_list', 	get_member_price_list($_REQUEST['goods_id']));//价格阶梯
		$this->assign('unit_list', 			get_unit_list());	//计重单位
		$this->assign('goods_type_list', 	goods_type_list($goods['goods_type']));/*商品类型*/		
		$this->display();
	}
	
	// 获取类型属性
	public function get_arrtibutes(){	
		$goods_id   	= 	empty($_GET['goods_id']) ? 0 : intval($_GET['goods_id']);
    	$goods_type 	= 	empty($_GET['goods_type']) ? 0 : intval($_GET['goods_type']);		
		$GoodsModel		=	new GoodsModel();
		$html			=	$GoodsModel->build_Attr_Html($goods_type, $goods_id);
		
		if ($this->isAjax()) {
			$this->ajaxReturn($html);
		}
	}
	
	// 添加关联商品
	public function  add_link_goods(){
	    $linked_array   = 	$_GET['add_ids'];
	    $linked_goods   = 	$_GET['JSON'];
	    $goods_id       = 	$linked_goods[0]; // 针对带有false,true的,要转化json_decode
	    $is_double      = 	( json_decode($linked_goods[1]) == true ) ? 0 : 1;
		
	    foreach ($linked_array AS $val){
	        if ($is_double){
	            $sql 	= 	"INSERT INTO " . 'ybr_link_goods' . " (goods_id, link_goods_id, is_double, admin_id) " .
	                    	"VALUES ('$val', '$goods_id', '$is_double', '1')";
	            M()->query($sql);	// 双向关联入库
	        }
	        $sql 		= 	"INSERT INTO " . 'ybr_link_goods' . " (goods_id, link_goods_id, is_double, admin_id) " .
	                		"VALUES ('$goods_id', '$val', '$is_double', '1')";
	        M()->query($sql);
	    }
	      // 返回数据
	    $GoodsModel	=	new GoodsModel();
	    $linked_goods   = $GoodsModel->get_linked_goods($goods_id);
	    $options        = array();
	
	    foreach ($linked_goods AS $val){
	        $options[] = array('value'  => $val['goods_id'],
	                        'text'      => $val['goods_name'],
	                        'data'      => '');
	    }
	    $return['content']	=	$options;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}

	// 删除关联商品
	public function drop_link_goods(){
		// 转为json数据
	    $drop_goods     	= 	$_GET['drop_ids'];
	    $drop_goods_ids 	= 	Utils::db_create_in($drop_goods);
	    $linked_goods   	= 	$_GET['JSON']; 	// 带有false,true的json数据,都需要转化
	    $goods_id       	= 	$linked_goods[0];
	    $is_signle      	= 	json_decode($linked_goods[1]);
	        
	    if (!$is_signle){
	        $sql = "DELETE FROM " .'ybr_link_goods' .
	                " WHERE link_goods_id = '$goods_id' AND goods_id " . $drop_goods_ids;
	    }else{
	        $sql = "UPDATE " .'ybr_link_goods' . " SET is_double = 0 ".
	                " WHERE link_goods_id = '$goods_id' AND goods_id " . $drop_goods_ids;
	    }
	    if ($goods_id == 0){
	        $sql .= " AND admin_id = '1'";
	    }
	    
	    M()->query($sql); // 删除关联商品
	
	    $sql = "DELETE FROM " . 'ybr_link_goods' . " WHERE goods_id = '$goods_id' AND link_goods_id " . $drop_goods_ids;
	    if ($goods_id == 0){
	        $sql .= " AND admin_id = '1'";
	    }
	    M()->query($sql);
		// 取出商品
	    $GoodsModel		=	new GoodsModel();
	    $linked_goods   = 	$GoodsModel->get_linked_goods($goods_id);
	    $options      	= 	array();
	
	    foreach ($linked_goods AS $val){
	        $options[] = array(
	                        'value' => $val['goods_id'],
	                        'text'  => $val['goods_name'],
	                        'data'  => '');
	    }
		$return['content']	=	$options;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}
	
	// 获取商品
	public function get_goods_list(){
		$GoodsModel		=	new GoodsModel();
		
		$datas			=	$GoodsModel->getGoodsList($_GET);
		$opt = array();
		foreach ($datas AS $key => $val){
	        $opt[] = array('value' => $val['goods_id'],
	                        'text' => $val['goods_name'],
	                        'data' => $val['shop_price']);
	    }
		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}
	
	// 添加配件
	public function add_group_goods(){		
		
	    $fittings   = 	$_GET['add_ids'];	// 配件商品id
	    $arguments  = 	$_GET['JSON'];
	    $goods_id   = 	$arguments[0]; 		// 当前商品id,新增的商品id为0
	    $price      = 	$arguments[1]; 		// 配件商品的价钱
	    
	    foreach ($fittings AS $val){
	        $sql = "INSERT INTO " . 'ybr_group_goods' . " (parent_id, goods_id, goods_price, admin_id) " .
	                "VALUES ('$goods_id', '$val', '$price', '1')"; // admin_id默认为admin:1
	        M()->query($sql);
	    }
	    // 返回数据
	    $GoodsModel	=	new GoodsModel();
	    $goodsList	=	$GoodsModel->get_group_goods($goods_id);	    
	    $opt = array();
		// 构造json数据
	    foreach ($goodsList AS $val) {
	        $opt[] = array('value'      => $val['goods_id'],
	                        'text'      => $val['goods_name'],
	                        'data'      => '');
	    }
	    
	    $return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
	    $this->ajaxReturn($return);
	}
	
	// 删除配件
	public function drop_group_goods(){
	    $fittings   = $_GET['drop_ids'];
	    $arguments  = $_GET['JSON'];
	    $goods_id   = $arguments[0];
	    $price      = $arguments[1];
		
	    $sql = "DELETE FROM " .'ybr_group_goods' .
	            " WHERE parent_id='$goods_id' AND " .Utils::db_create_in($fittings, 'goods_id');
	    if ($goods_id == 0){
	        $sql .= " AND admin_id = '1'";
	    }
	    // 移除需要删除的配件
	    M()->query($sql);
	    // 返回数据
	    $GoodsModel	=	new GoodsModel();
	    $arr 		= 	$GoodsModel->get_group_goods($goods_id);
	    $opt 		= 	array();
	
	    foreach ($arr AS $val){
	        $opt[] = array('value'      => $val['goods_id'],
	                        'text'      => $val['goods_name'],
	                        'data'      => '');
	    }
		
	  	$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
	    $this->ajaxReturn($return);
	}
	
	// 获取关联文章
	public function get_article_list(){
	    $filters 	= 	$_GET['JSON'];
	    
	    $GoodsModle	=	new GoodsModel();
	    // 传入条件
	    $articleList=	$GoodsModle->getArticleList($filters);
	    
	    $arr        = array();
	    foreach($articleList as $article){
	    	$arr[]  = array('value' => $article['article_id'], 'text' => $article['title'], 'data'=>'');
	    }
	    $return['content']	=	$arr;
		$return['error']	=	0;
		$return['message']	=	"";
	    $this->ajaxReturn($return);
	}
	
	// 添加关联文章
	public function add_goods_article(){		
	    $articles   	= 	$_GET['add_ids'];
	    $arguments 	 	= 	$_GET['JSON'];
	    $goods_id   	= 	$arguments[0];
	
	    foreach ($articles AS $val){
	        $sql 		= 	"INSERT INTO " . 'ybr_goods_article' . " (goods_id, article_id, admin_id) " .
	                		"VALUES ('$goods_id', '$val', '1')";
	        M()->query($sql); // 入库
	    }
		
	    $GoodsModel		=	new GoodsModel();	    
	    $datas			=	$GoodsModel->get_goods_articles($goods_id);	
	    $opt 			=	array();
	
	    foreach ($datas AS $val){
	        $opt[] = array('value'      => $val['article_id'],
	                        'text'      => $val['title'],
	                        'data'      => '');
	    }
	    $return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
	    $this->ajaxReturn($return);
	}
	
	// 删除关联文章
	public function drop_goods_article(){	
	    $articles   = $_GET['drop_ids'];
	    $arguments  = $_GET['JSON'];
	    $goods_id   = $arguments[0];
	
	    $sql = "DELETE FROM " . 'ybr_goods_article' . " WHERE " . Utils::db_create_in($articles, "article_id") . " AND goods_id = '$goods_id'";
	    M()->query($sql); // 删除关联文章
	
	    $GoodsModel		=	new GoodsModel();	    
	    $datas			=	$GoodsModel->get_goods_articles($goods_id);
	    $opt 			= 	array();
	
	    foreach ($datas AS $val){
	        $opt[] = array('value'      => $val['article_id'],
	                        'text'      => $val['title'],
	                        'data'      => '');
	    }
		$return['content']	=	$opt;
		$return['error']	=	0;
		$return['message']	=	"";
	    $this->ajaxReturn($return);
	}
	
	/**
	 * 校验商品goods_sn的有效性
	 *
	 */
	public function check_goods_sn(){
				
	    $goods_id 	= 	intval( $_REQUEST['goods_id'] );
	    $goods_sn 	= 	htmlspecialchars( trim($_REQUEST['goods_sn']) );
	    
	    $GoodsModel	=	new GoodsModel();
	    
	    if(empty($goods_sn)){
	    	$this->return['message']	=	"商品货号商品货号已存在";
			$this->return['error']		=	1;
		    $this->ajaxReturn($this->return);
	    }
	    
	    /* 检查是否重复 */
	    if (!$GoodsModel->is_only('goods_sn', $goods_sn, $goods_id)){
			$this->return['message']	=	"商品货号商品货号已存在";
			$this->return['error']		=	1;
		    $this->ajaxReturn($this->return);
	    }
	    if(!empty($goods_sn)){
	        $sql	=	"SELECT goods_id FROM ". 'ybr_products' . "WHERE product_sn='$goods_sn'";
	        if( M()->query($sql) ){
	       		$this->return['message']	=	"商品货号商品货号已存在";
	       		$this->return['error']		=	1;
	       		$this->ajaxReturn($this->return);
	        }
	    }
	    $this->ajaxReturn($this->return);
	}	
	
	public function auto_create(){
		$goods_id 	= 	intval( $_REQUEST['goods_id'] );
		
		if(empty($goods_id)){
	    	$datas			=	M('Goods')->field(" MAX(goods_id) + 1 as max_goods_id")->find();
	    	$goods_id		=	$datas['max_goods_id'];	    	
		}
		$goods_sn			=	GoodsModel::generate_goods_sn($goods_id);
		if($goods_sn){
			$this->ajaxReturn(1,$goods_sn,0);
		}
		else{
			$this->ajaxReturn(0,$goods_sn,0);
		}
	}
	
	/**
	 * 处理添加商品
	 *  
	 */
	public function add_goods_ok(){
		import('ORG.Net.UploadFile'); /* 导入图片上传类 */
		$img_dir	=	"./Public/Upload/images/";		
		$code 		= 	empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']); /* 判断是否为虚拟 */
		$datas		=	array();
		/* 插入还是更新的标识 */
	    $is_insert 	= 	empty($_REQUEST['act']) ? "insert":$_REQUEST['act'];
		
	    /* 检查货号是否重复 */
	    if ($_POST['goods_sn']){
	        $sql 	= 	"SELECT COUNT(*) count FROM " . 'ybr_goods' . " WHERE goods_sn = '$_POST[goods_sn]' AND is_delete = 0 AND goods_id <> '$_POST[goods_id]'";
	       	$result	=	M()->query($sql);
	        if($result[0]['count'] > 0){
	        	$this->error("商品货号已存在");
	        }
	    }
	
	    /* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
	    if (isset($_FILES['goods_img']['error'])){ // php 4.2 版本才支持 error
		    // 常规性判断
   	        if ($_FILES['goods_img']['error'] == 0){
   	        	if (!Utils::check_img_type($_FILES['goods_img']['type'])){
   	        		$this->error("上传商品图片格式不正确");
   	        	}
	        }
	        elseif ($_FILES['goods_img']['error'] == 1){
	            $this->error("上传商品图片大小超过系统的预设值,请联系服务器管理员: 15119298443");
	        }
	        elseif ($_FILES['goods_img']['error'] == 2){
	             $this->error("上传商品图片大小超过表单的预设值,请联系界面程序员: 15119298443");
	        }
		    
   	        // 商品缩略图
	        if (isset($_FILES['goods_thumb'])){
	            if ($_FILES['goods_thumb']['error'] == 0){
		            if (!Utils::check_img_type($_FILES['goods_thumb']['type'])){
	   	        		$this->error("上传商品缩略图片格式不正确");
	   	        	}
	            }
	            elseif ($_FILES['goods_thumb']['error'] == 1){
	                $this->error("上传商品缩略图片大小超过系统的预设值,请联系服务器管理员: 15119298443");
	            }
	            elseif ($_FILES['goods_thumb']['error'] == 2){
	                $this->error("上传商品缩略图片大小超过系统的预设值,请联系服务器管理员: 15119298443");
	            }
	        }
		    
	        // 相册图片
	        foreach ($_FILES['img_url']['error'] AS $key => $value){
	            if ($value == 0){
	             	if (!Utils::check_img_type($_FILES['img_url']['type'][$key])){
	   	        		$this->error("上传商品" .  ($key + 1) . "图片格式不正确");
	   	        	}
	            }
	            elseif ($value == 1){
	                $this->error("上传商品相册" . ($key + 1) . "图片大小超过系统的预设值,请联系服务器管理员: 15119298443");
	            }
	            elseif ($_FILES['img_url']['error'] == 2){
	                $this->error("上传商品相册" . ($key + 1) . "图片大小超过表单的预设值,请联系服务器管理员: 15119298443");
	            }
	        }
	    }
	   
	    /* 处理商品图片 */
	    $goods_img        = '';  // 初始化商品图片
	    $goods_thumb      = '';  // 初始化商品缩略图
	    $original_img     = '';  // 初始化原始图片
	    $old_original_img = '';  // 初始化原始图片旧图
		
	    // 如果上传了商品图片,相应处理
	    if (($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none') or (($_POST['goods_img_url'] != $_LANG['lab_picture_url'] && $_POST['goods_img_url'] != 'http://') && $is_url_goods_img = 1)){
	    	if ($_REQUEST['goods_id'] > 0){
   	            /* 删除原来的图片文件 */
	            $sql = "SELECT goods_thumb, goods_img, original_img " .
	                    " FROM " . 'ybr_goods' .
	                    " WHERE goods_id = '$_REQUEST[goods_id]'";
	            //$row = $db->getRow($sql);
	            $row	=	M()->query($sql);
	            
	            if ($row['goods_thumb'] != '' && is_file($img_dir . $row['goods_thumb'])){
	                @unlink($img_dir . $row['goods_thumb']);
	            }
	            if ($row['goods_img'] != '' && is_file($img_dir . $row['goods_img'])){
	                @unlink($img_dir . $row['goods_img']);
	            }
	            if ($row['original_img'] != '' && is_file($img_dir . $row['original_img'])){
	                /* 先不处理，以防止程序中途出错停止 */
	                //$old_original_img = $row['original_img']; //记录旧图路径
	            }
	    	}
	    	
		    /* 是否自动生成缩略图  */
	    	if($_POST['auto_thumb'] ){	    		
	    		/* 上传原图,并且自动生成缩略图  */
			    $upload 			= 	new UploadFile();	// 实例化上传类
			    $upload->maxSize  	= 	3000000 ;			// 设置附件上传大小
			    $upload->allowExts  = 	array('jpg', 'gif', 'png', 'jpeg');	// 设置附件上传类型
			    $ymd              	=   date('Ymd');
			    $upload->savePath 	=  	'./Public/Upload/images/' . $ymd . '/';			// 设置附件上传目录
			    $upload->thumb 		= 	true;
			    $upload->thumbPrefix 	=	'thumb_';
				$upload->thumbMaxWidth 	= 	'300';		//设置缩略图最大宽度
				$upload->thumbMaxHeight = 	'300';		//设置缩略图最大高度
				
				$info				=	$upload->uploadOne($_FILES['goods_img'], $upload->savePath);		    
			    if($info){
			    	$goods_img		=	$ymd . '/' . $info[0]['savename'];
			    	$goods_thumb	=	$ymd . '/' . 'thumb_' . $info[0]['savename'];
			    }else{
			       $errorMsg		=	$upload->getErrorMsg();
			    }
	    	}
	    	else{
	    		// 上传商品图片
	    	 	$upload 			= 	new UploadFile();	// 实例化上传类
			    $upload->maxSize  	= 	3000000 ;			// 设置附件上传大小
			    $upload->allowExts  = 	array('jpg', 'gif', 'png', 'jpeg');	// 设置附件上传类型
			    $ymd              	=   date('Ymd');
			    $upload->savePath 	=  	'./Public/Upload/images/' . $ymd . '/';			// 设置附件上传目录
				
				$info				=	$upload->uploadOne($_FILES['goods_img'], $upload->savePath);		    
			    if($info){
			    	//t($info);
			    	$goods_img		=	$ymd . '/' . $info[0]['savename'];
			    }else{
			       $errorMsg		=	$upload->getErrorMsg();
			    }
	    		
	    		// 上传缩略图
	    		$upload2 			= 	new UploadFile();	// 实例化上传类
			    $upload2->maxSize  	= 	3000000 ;			// 设置附件上传大小
			    $upload2->allowExts = 	array('jpg', 'gif', 'png', 'jpeg');	// 设置附件上传类型
			    $ymd              	=   date('Ymd');
			    $upload2->savePath 	=  	'./Public/Upload/images/' . $ymd . '/';			// 设置附件上传目录
				
				$info				=	$upload2->uploadOne($_FILES['goods_thumb'], $upload2->savePath);		    
			    if($info){
			    	//t($info);
			    	$goods_thumb	=	$ymd . '/' . $info[0]['savename'];
			    }else{
			       $errorMsg				=	$upload->getErrorMsg();
			    }	    		
	    	}  	
	    }
	    	    
	    /* 如果没有输入商品货号则自动生成一个商品货号 */
	    if (empty($_POST['goods_sn'])){
	        $max_id     		= 	"SELECT MAX(goods_id) + 1 FROM  ybr_goods";
	        $goods_sn   		= 	GoodsModel::generate_goods_sn($max_id);
	        $datas['goods_sn']	=	$goods_sn;    
	    }
	    else{
	        $goods_sn  		 	= 	$_POST['goods_sn'];
	        $datas['goods_sn']	=	$goods_sn;
	    }
	    
	    //t("");
	    //echo "货号：" . $datas['goods_sn'] . '------';
	    
	    /* 处理商品数据 */		
	    $datas['shop_price']		=	!empty($_POST['shop_price']) ? $_POST['shop_price'] : 0;
	    $datas['market_price']		=	!empty($_POST['market_price']) ? $_POST['market_price'] : 0;
	    $datas['promote_price']		=	!empty($_POST['promote_price']) ? $_POST['promote_price'] : 0;
	    $datas['is_promote']		=	empty($datas['promote_price']) ? 0 : 1;
	    $datas['promote_start_date']=	($datas['is_promote'] && !empty($_POST['promote_start_date'])) ? Utils::local_strtotime($_POST['promote_start_date']) : 0;
	    $datas['promote_end_date']	=	($datas['is_promote'] && !empty($_POST['promote_end_date'])) ? Utils::local_strtotime($_POST['promote_end_date']) : 0;
	    $datas['goods_weight']		=	!empty($_POST['goods_weight']) ? $_POST['goods_weight'] * $_POST['weight_unit'] : 0;
	    $datas['is_best']			=	isset($_POST['is_best']) ? 1 : 0;
	    $datas['is_new']			=	isset($_POST['is_new']) ? 1 : 0;
	    $datas['is_hot']			=	isset($_POST['is_hot']) ? 1 : 0;
	    $datas['is_on_sale']		=	isset($_POST['is_on_sale']) ? 1 : 0;
	    $datas['is_alone_sale']		=	isset($_POST['is_alone_sale']) ? 1 : 0;
	    $datas['is_shipping']		=	isset($_POST['is_shipping']) ? 1 : 0;
	    $datas['goods_number']		=	isset($_POST['goods_number']) ? $_POST['goods_number'] : 0;
	    $datas['warn_number']		=	isset($_POST['warn_number']) ? $_POST['warn_number'] : 0;
	    $datas['goods_type']		=	isset($_POST['goods_type']) ? $_POST['goods_type'] : 0;
	    $datas['give_integral']		=	isset($_POST['give_integral']) ? intval($_POST['give_integral']) : '-1';
	    $datas['rank_integral']		=	isset($_POST['rank_integral']) ? intval($_POST['rank_integral']) : '-1';
	    $datas['suppliers_id']		=	isset($_POST['suppliers_id']) ? intval($_POST['suppliers_id']) : '-1';
	    $datas['goods_name_style']	=	$_POST['goods_name_color'] . '+' . $_POST['goods_name_style'];
	    $datas['cat_id']			=	$_POST['cat_id'] . '+' . $_POST['cat_id'];
	    $datas['brand_id']			=	$_POST['brand_id'] . '+' . $_POST['brand_id'];
	    $datas['goods_brief']		=	$_POST['goods_brief'];
	    $datas['seller_note']		=	$_POST['seller_note'];
	    $datas['goods_desc']		=	$_POST['goods_desc'];
		// 商品图片
		$datas['goods_img']			=	$goods_img == '' ? "" : $goods_img;
		$datas['goods_thumb']		=	$goods_thumb == '' ? "" : $goods_thumb;	
		
		// 关键字处理
		$keywords_arr 				= 	explode(" ", $_POST['keywords']);
        $keywords_arr 				= 	array_flip($keywords_arr);
        if (isset($keywords_arr[''])){
            unset($keywords_arr['']);
        }
        $datas['keywords']			=	join(' ', array_flip($keywords_arr));	
		
		// 数据模型
		$GoodsModel					=	M('Goods');
		$goods_id					=	'';
	    		
	    /* 入库 */
	    if ($is_insert == 'insert'){
	    	$datas['goods_name']	=	$_REQUEST['goods_name'];
	    	$datas['goods_sn']		=	$_REQUEST['goods_sn'];	    	  
			$datas['add_time']		=	Utils::gmtime();	  
	    	// 商品图片图片
	        if ($goods_img){
	            $datas['goods_img']		=	$goods_img;
	        }
	        if ($goods_thumb){
	            $datas['goods_thumb']	=	$goods_thumb;
	        }
	        // 若为虚拟商品
	        if ($code != ''){
	            $datas['is_real']			=	0;
	            $datas['extension_code']	=	'virtual_card';
	        }
	        
	        $goods_id						=	$GoodsModel->add($datas);
	    }
	    else{
	        /* 如果有上传图片，删除原来的商品图 */	        
	        $row			=	$GoodsModel->field(" goods_thumb, goods_img, original_img ")->where(" goods_id = '$_REQUEST[goods_id]' ")->select();
	        
	        if ($goods_img && $row['goods_img'] && !goods_parse_url($row['goods_img'])){
	            @unlink(ROOT_PATH . $row['goods_img']);
	            @unlink(ROOT_PATH . $row['original_img']);
	        }
	
	        if ($goods_thumb && $row['goods_thumb'] && !goods_parse_url($row['goods_thumb'])){
	            @unlink(ROOT_PATH . $row['goods_thumb']);
	        }
			
	        // 构造存储数组
	        $datas	['goods_name']				=	$_POST['goods_name'];	
	        $datas	['goods_sn']				=	$_POST['goods_sn'];	
	        $datas	['cat_id']					=	$_POST['cat_id'];	
	        $datas	['brand_id']				=	$_POST['brand_id'];	
	        $datas	['shop_price']				=	$_POST['shop_price'];	
	        $datas	['market_price']			=	$_POST['market_price'];	
	        $datas	['is_promote']				=	$_POST['is_promote'];	
	        $datas	['promote_price']			=	$_POST['promote_price'];	
	        $datas	['promote_start_date']		=	$_POST['promote_start_date'];	
	        $datas	['promote_end_date']		=	$_POST['promote_end_date'];	
	        $datas	['suppliers_id']			=	$_POST['suppliers_id'];	
	        $datas	['last_update']				=	Utils::gmtime();	  // 更新时间
	        
	        /* 如果有上传图片，需要更新数据库 */
	        if ($goods_img){
	            $datas['goods_img']	=	$goods_img;
	        }
	        if ($goods_thumb){
	            $datas['goods_thumb']	=	$goods_thumb;
	        }
	        if ($code != ''){
	            $datas['is_real']			=	0;
	            $datas['extension_code']	=	'virtual_card';
	        }	        
	        // 更新数据
	        $GoodsModel->where(" goods_id='{$_REQUEST['goods_id']}' ")->save($datas);   
	    }
	    
	    /* 商品编号 */
	    $goods_id = $is_insert ? $goods_id : $_REQUEST['goods_id'];
	    
//	    echo "------------------------------------------------------------------";
//	    t($goods_id);
//	    echo "------------------------------------------------------------------";
		
	    /* 处理属性  */ 
	    if((isset($_POST['attr_id_list']) && isset($_POST['attr_value_list'])) || (empty($_POST['attr_id_list']) && empty($_POST['attr_value_list']))){
	        // 取得原有的属性值
	        $goods_attr_list 	= 	array();	
	        $keywords_arr 		= 	explode(" ", $_POST['keywords']);
	
	        $keywords_arr 		= 	array_flip($keywords_arr);
	        if (isset($keywords_arr[''])){
	            unset($keywords_arr['']);
	        }
	
	        $sql 				= 	"SELECT attr_id, attr_index FROM " . 'ybr_attribute' . " WHERE cat_id = '{$_POST['goods_type']}'";
			$attr_res			=	M()->query($sql);	
			
	        $attr_list 			= 	array();
			foreach($attr_res as $row){
				 $attr_list[$row['attr_id']] = $row['attr_index'];
			}
	        // 查询该商品的所有属性
	        $sql 	= 	"SELECT g.*, a.attr_type FROM ybr_goods_attr  AS g  LEFT JOIN  ybr_attribute  AS a ON a.attr_id = g.attr_id WHERE g.goods_id = $goods_id ";
	        $res	=	M()->query($sql);
			foreach($res as $row){
				$goods_attr_list[$row['attr_id']][$row['attr_value']] = array('sign' => 'delete', 'goods_attr_id' => $row['goods_attr_id']);
			}
			
	        // 循环提交过来的现有的，根据原有的做相应处理
	        if(isset($_POST['attr_id_list'])){
	            foreach ($_POST['attr_id_list'] AS $key => $attr_id){
	                $attr_value = $_POST['attr_value_list'][$key];
	                $attr_price = $_POST['attr_price_list'][$key];
	                if (!empty($attr_value)){
	                    if (isset($goods_attr_list[$attr_id][$attr_value])){
	                        // 如果原来有，标记为更新
	                        $goods_attr_list[$attr_id][$attr_value]['sign'] = 'update';
	                        $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
	                    }
	                    else{
	                        // 如果原来没有，标记为新增
	                        $goods_attr_list[$attr_id][$attr_value]['sign'] = 'insert';
	                        $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
	                    }
	                    $val_arr = explode(' ', $attr_value);
	                    foreach ($val_arr AS $k => $v){
	                        if (!isset($keywords_arr[$v]) && $attr_list[$attr_id] == "1"){
	                            $keywords_arr[$v] = $v;
	                        }
	                    }
	                }
	            }
	        }	        
	        
	        /* 插入、更新、删除数据 */
	        foreach ($goods_attr_list as $attr_id => $attr_value_list){
	            foreach ($attr_value_list as $attr_value => $info){
	                if ($info['sign'] == 'insert'){
	                    $sql 	= 	"INSERT INTO " . 'ybr_goods_attr' . " (attr_id, goods_id, attr_value, attr_price)". "VALUES ('$attr_id', '$goods_id', '$attr_value', '$info[attr_price]')";
	                }
	                elseif ($info['sign'] == 'update'){
	                    $sql 	= 	"UPDATE " . 'ybr_goods_attr' . " SET attr_price = '$info[attr_price]' WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1";
	                }
	                else{
	                    $sql 	= 	"DELETE FROM " . 'ybr_goods_attr' . " WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1";
	                }
	                M()->query($sql);
	            }
	        }
	    }
	    
	    /* 处理会员价格 */
	    if (isset($_POST['user_rank']) && isset($_POST['user_price'])){
	        GoodsModel::handle_member_price($goods_id, $_POST['user_rank'], $_POST['user_price']);
	    }
	
	    /* 处理优惠价格 */
	    if (isset($_POST['volume_number']) && isset($_POST['volume_price'])){
	        $temp_num = array_count_values($_POST['volume_number']);
	        foreach($temp_num as $v){
	            if ($v > 1){
	                $this->error("优惠数量重复!");
	                break;
	            }
	        }
	        GoodsModel::handle_volume_price($goods_id, $_POST['volume_number'], $_POST['volume_price']);
	    }
	    
	    /* 处理扩展分类 */
	    if (isset($_POST['other_cat'])){
	       	GoodsModel::handle_other_cat($goods_id, array_unique($_POST['other_cat']));
	    }
	
	    if ($is_insert){
	        /* 处理关联商品 */
	        GoodsModel::handle_link_goods($goods_id);
	
	        /* 处理组合商品 */
	        GoodsModel::handle_group_goods($goods_id);
	
	        /* 处理关联文章 */
	        GoodsModel::handle_goods_article($goods_id);
	    }    
	    
		//通过多文件上传插件达到多文件上传的结果
		$img_id_array	=	$_REQUEST['img_id'];
		$img_desc_array	=	$_REQUEST['img_desc'];
		$img_array		=	array();
		foreach ($img_id_array as $k =>$img_id) {
			$img_array[$img_id]= $img_desc_array[$k];
		}
		GoodsModel::hangdle_goods_gallery($img_array,$goods_id);

	    /* cookie记录上一次选择的分类和品牌 */
	    //setcookie('ECSCP[last_choose]', $catgory_id . '|' . $brand_id, gmtime() + 86400);
        $url		=	U('goods/goods_list') . '?product_list&goods_id=' . $goods_id;
        $this->success("操作成功,将为您跳转页面",$url);
	}
	
	// 商品添加相册图片
	public function add_goods_gallery(){		
		import('ORG.Net.UploadFile'); /* 导入图片上传类 */
		// 商品相册图片,上传并生成缩略图
	    $upload3 			= 	new UploadFile();		// 实例化上传类
	    $upload3->maxSize  	= 	3000000 ;				// 设置附件上传大小
	    $upload3->allowExts = 	array('jpg', 'gif', 'png', 'jpeg');	// 设置附件上传类型
	    $ymd              	=   date('Ymd');
	    $upload3->savePath 	=  	'./Public/Upload/images/' . $ymd . '/';			// 设置附件上传目录
	    $upload3->thumb 			= 	true;
	    $upload3->thumbPrefix 		=	'thumb_';
		$upload3->thumbMaxWidth 	= 	'600';			//设置缩略图最大宽度
		$upload3->thumbMaxHeight 	= 	'300';			//设置缩略图最大高度
		//$upload3->saveRule		 	= 	'date';		//设置缩略图最大高度
		
		if($upload3->upload()){
			$info					=	$upload3->getUploadFileInfo();
			//t($info);
			$datas['img_url']		=	$ymd . '/' . $info[0]['savename'];
			$datas['thumb_url']		=	$ymd . '/' . 'thumb_' . $info[0]['savename'];			
			$img_id					=	M('GoodsGallery')->add($datas);
			
			$msg['id']				=	$img_id;
			$msg['thumb_url']		=	$datas['thumb_url'];
			$msg['status']			=	1;			
			echo json_encode($msg);
		}
		else{
			$msg['status']			=	0;
			echo $upload3->getErrorMsg();
			//echo json_encode($msg);
		}
	}
	
	// 商品删除相册图片
	public function del_goods_gallery(){
		$img_id		=	$_POST['img_id'];
		
		//$img_info	=	M('GoodsGallery')->getField("img_url")->where("img_id='{$img_id}'")->find();
		
		M('GoodsGallery')->where("img_id = '{$img_id}'")->delete();
		$this->ajaxReturn(1,"操作成功",1);
	}
	
	// 删除商品
	public function del_goods(){
		
	}
	
	// 修改商品
	public function mod_goods(){
		
		$CommonModel	=	new CommonModel();
		$GoodsCatModel		=	new GoodsCatModel();
		
	    $is_add 		= 	$_REQUEST['act'] == 'add'; // 添加还是编辑的标识
	    $is_copy 		= 	$_REQUEST['act'] == 'copy'; //是否复制
	    $code 			=	empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
	    $code			=	$code == 'virual_card' ? 'virual_card': '';
	
	    /*供货商名*/
	    $suppliers_list_name 	= 	suppliers_list_name();
	    
	    $suppliers_exists 		= 	1;
	    if (empty($suppliers_list_name)){
	        $suppliers_exists 	= 	0;
	    }
	    $this->assign('suppliers_exists', $suppliers_exists);
	    $this->assign('suppliers_list_name', $suppliers_list_name);
	    unset($suppliers_list_name, $suppliers_exists);
	
		/* 商品信息 */
        $sql = "SELECT * FROM " . 'ybr_goods' . " WHERE goods_id = '$_REQUEST[goods_id]'";
        $goods = $CommonModel->getRow($sql);

        /* 虚拟卡商品复制时, 将其库存置为0
        if ($is_copy && $code != ''){
            $goods['goods_number'] = 0;
        }*/

        if (empty($goods) === true){
            /* 默认值 */
            $goods = array(
                'goods_id'      => 0,
                'goods_desc'    => '',
                'cat_id'        => 0,
                'is_on_sale'    => '1',
                'is_alone_sale' => '1',
                'is_shipping' => '0',
                'other_cat'     => array(), // 扩展分类
                'goods_type'    => 0,       // 商品类型
                'shop_price'    => 0,
                'promote_price' => 0,
                'market_price'  => 0,
                'integral'      => 0,
                'goods_number'  => 1,
                'warn_number'   => 1,
                'promote_start_date' => local_date('Y-m-d'),
                'promote_end_date'   => local_date('Y-m-d', gmstr2tome('+1 month')),
                'goods_weight'  => 0,
                'give_integral' => -1,
                'rank_integral' => -1
            );
        }

        /* 获取商品类型存在规格的类型 */
        $specifications 			= 	get_goods_type_specifications();
        $goods['specifications_id'] = 	$specifications[$goods['goods_type']];
        $_attribute					= 	get_goods_specifications_list($goods['goods_id']);
        $goods['_attribute'] 		= 	empty($_attribute) ? '' : 1;

        /* 根据商品重量的单位重新计算 */
        if ($goods['goods_weight'] > 0){
            $goods['goods_weight_by_unit'] 	= 	($goods['goods_weight'] >= 1) ? $goods['goods_weight'] : ($goods['goods_weight'] / 0.001);
        }

        if (!empty($goods['goods_brief'])){
            //$goods['goods_brief'] = trim_right($goods['goods_brief']);
            $goods['goods_brief'] 			= 	$goods['goods_brief'];
        }
        if (!empty($goods['keywords'])){
            //$goods['keywords']    = trim_right($goods['keywords']);
            $goods['keywords']    			= 	$goods['keywords'];
        }

        /* 如果不是促销，处理促销日期 */
        if (isset($goods['is_promote']) && $goods['is_promote'] == '0'){
            unset($goods['promote_start_date']);
            unset($goods['promote_end_date']);
        }
        else{
            $goods['promote_start_date'] = local_date('Y-m-d', $goods['promote_start_date']);
            $goods['promote_end_date'] = local_date('Y-m-d', $goods['promote_end_date']);
        }

        /* 如果是复制商品，处理 */
        if ($_REQUEST['act'] == 'copy'){
            // 商品信息
            $goods['goods_id'] 		= 	0;
            $goods['goods_sn'] 		= 	'';
            $goods['goods_name'] 	= 	'';
            $goods['goods_img'] 	= 	'';
            $goods['goods_thumb'] 	= 	'';
            $goods['original_img'] 	= 	'';

            // 扩展分类不变

            // 关联商品
            $sql 	= 	"DELETE FROM " . 'ybr_link_goods' .
                    	" WHERE (goods_id = 0 OR link_goods_id = 0)" .
                    	" AND admin_id = '$_SESSION[admin_id]'";
            M()->execute($sql);

            $sql 	= 	"SELECT '0' AS goods_id, link_goods_id, is_double, '$_SESSION[admin_id]' AS admin_id" .
                    	" FROM " . 'ybr_link_goods' .
                    	" WHERE goods_id = '$_REQUEST[goods_id]' ";
            $res 	= 	M()->query($sql);
            foreach($res as $row){
            	$CommonModel->autoExecute('ybr_link_goods', $row, 'INSERT');
            }
            
            $sql 	= 	"SELECT goods_id, '0' AS link_goods_id, is_double, '$_SESSION[admin_id]' AS admin_id" .
                    	" FROM " . 'ybr_link_goods' .
                    	" WHERE link_goods_id = '$_REQUEST[goods_id]' ";
            $res 	= 	M()->query($sql);
            foreach($res as $row){
            	$CommonModel->autoExecute('ybr_link_goods', $row, 'INSERT');
            }
            
            // 配件
            $sql 	= 	"DELETE FROM " . 'ybr_group_goods' .
                    	" WHERE parent_id = 0 AND admin_id = '$_SESSION[admin_id]'";
            M()->execute($sql);

            $sql 	= 	"SELECT 0 AS parent_id, goods_id, goods_price, '$_SESSION[admin_id]' AS admin_id " .
                    	"FROM " . 'ybr_group_goods' .
                    	" WHERE parent_id = '$_REQUEST[goods_id]' ";
            $res 	= 	M()->query($sql);
            foreach($res as $row){
            	$CommonModel->autoExecute('group_goods', $row, 'INSERT');
            }
            
            // 关联文章
            $sql 	= 	"DELETE FROM " . 'ybr_goods_article' .
                    	" WHERE goods_id = 0 AND admin_id = '$_SESSION[admin_id]'";
            M()->execute($sql);

            $sql 	= 	"SELECT 0 AS goods_id, article_id, '$_SESSION[admin_id]' AS admin_id " .
                    	"FROM " . 'ybr_goods_article' .
                    	" WHERE goods_id = '$_REQUEST[goods_id]' ";
            $res 	= 	M()->query($sql);
            foreach($res as $row){
            	$CommonModel->autoExecute('goods_article', $row, 'INSERT');
            }
            
            // 图片不变

            // 商品属性
            $sql 	= 	"DELETE FROM " . 'ybr_goods_attr' . " WHERE goods_id = 0";
            $CommonModel->query($sql);

            $sql 	= 	"SELECT 0 AS goods_id, attr_id, attr_value, attr_price " .
                    	"FROM " . 'ybr_goods_attr' .
                    	" WHERE goods_id = '$_REQUEST[goods_id]' ";
            $res 	= 	M()->query($sql);
            foreach($res as $row){
            	$CommonModel->autoExecute('goods_attr', addslashes_deep($row), 'INSERT');
            }
        }

        // 扩展分类
        $other_cat_list 	= 	array();
        $sql 				= 	"SELECT cat_id FROM " . 'ybr_goods_cat' . " WHERE goods_id = '$_REQUEST[goods_id]'";
        $goods['other_cat'] = 	$CommonModel->getCol($sql);
        
        foreach ($goods['other_cat'] AS $cat_id){
            $other_cat_list[$cat_id] = cat_list(0, $cat_id);
        }
        $this->assign('other_cat_list', $other_cat_list);

        $link_goods_list    = 	get_linked_goods($goods['goods_id']); // 关联商品
        $group_goods_list   = 	get_group_goods($goods['goods_id']); // 配件
        $goods_article_list = 	get_goods_articles($goods['goods_id']);   // 关联文章

        /* 商品图片路径 
        if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 10) && !empty($goods['original_img'])){
            $goods['goods_img'] 	= 	get_image_path($_REQUEST['goods_id'], $goods['goods_img']);
            $goods['goods_thumb'] 	=	 get_image_path($_REQUEST['goods_id'], $goods['goods_thumb'], true);
        }*/

        /* 图片列表 */
        M('GoodsGallery')->where("goods_id = 0")->delete(); // 把goods_id=0的图片清除掉
        $sql 				= 	"SELECT * FROM " . 'ybr_goods_gallery' . " WHERE goods_id = '$goods[goods_id]'";
        $img_list 			= 	M()->query($sql);

        /* 格式化相册图片路径 */
        if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 0)){
            foreach ($img_list as $key => $gallery_img){
                $gallery_img[$key]['img_url'] = get_image_path($gallery_img['goods_id'], $gallery_img['img_original'], false, 'gallery');
                $gallery_img[$key]['thumb_url'] = get_image_path($gallery_img['goods_id'], $gallery_img['img_original'], true, 'gallery');
            }
        }
        else{
            foreach ($img_list as $key => $gallery_img){
                $gallery_img[$key]['thumb_url'] = '../' . (empty($gallery_img['thumb_url']) ? $gallery_img['img_url'] : $gallery_img['thumb_url']);
            }
        }
	 	
	    /* 模板赋值 */
	    $this->assign('code',    				$code);	    
	    $this->assign('goods', 					$goods);
	    $this->assign('goodsCatList', 			$GoodsCatModel->getCategoryList()); //分类列表
	    $this->assign('brand_list', 			get_brand_list());
	    $this->assign('unit_list', 				get_unit_list());
	    $this->assign('user_rank_list', 		get_user_rank_list());
	    $this->assign('weight_unit', 			($goods['goods_weight'] >= 1 ? '1' : '0.001'));	    	  	
	    $this->assign('member_price_list', 		get_member_price_list($_REQUEST['goods_id']));	    
	    $this->assign('link_goods_list', 		$link_goods_list);
	    $this->assign('group_goods_list', 		$group_goods_list);
	    $this->assign('goods_article_list', 	$goods_article_list);
	    $this->assign('img_list', 				$img_list);
	    $this->assign('goods_type_list', 		goods_type_list($goods['goods_type']));
	    //$this->assign('gd', 					gd_version());
	    //$this->assign('cfg', 					$_CFG);
	    //$this->assign('thumb_width', 			$_CFG['thumb_width']);
	    //$this->assign('thumb_height', 		$_CFG['thumb_height']);
	    $this->assign('goods_attr_html', 		build_attr_html($goods['goods_type'], $goods['goods_id']));/*商品类型属性*/
	    /*数量-价格等级*/
	    $volume_price_list 			= 	'';
	    if(isset($_REQUEST['goods_id'])){
	   	 	$volume_price_list 		= 	get_volume_price_list($_REQUEST['goods_id']);
	    }
	    if (empty($volume_price_list)){
	        $volume_price_list 		= 	array('0'=>array('number'=>'','price'=>''));
	    }
	    $this->assign('volume_price_list', $volume_price_list); 

	    //t($goods);
	    $this->display();
	}
	
	// 处理修改商品
	public function mod_goods_ok(){		
		import('ORG.Net.UploadFile'); /* 导入图片上传类 */
		$img_dir		=	"./Public/upload/images/";
		
		$CommonModel	=	new CommonModel();
		
		$goods_id		=	intval($_REQUEST['goods_id']);
	    $code 			= 	empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
	    /* 是否处理缩略图
	    $proc_thumb = 	(isset($GLOBALS['shop_id']) && $GLOBALS['shop_id'] > 0)? false : true; */
	
	    /* 检查货号是否重复 */
	    if ($_POST['goods_sn']){
	        $sql 		= 	"SELECT COUNT(*) FROM " . 'ybr_goods' .
	                		" WHERE goods_sn = '$_POST[goods_sn]' AND is_delete = 0 AND goods_id <> '$_POST[goods_id]'";
	        if ($CommonModel->getOne($sql) > 0){
	            $this->error("商品货号已经存在了");
	        }
	    }
	
	    /* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
	    if (isset($_FILES['goods_img']['error'])) // php 4.2 版本才支持 error
	    {
	        // 最大上传文件大小
	        $php_maxsize = ini_get('upload_max_filesize');
	        $htm_maxsize = '2M';
	
	        // 商品图片
	        if ($_FILES['goods_img']['error'] == 0)
	        {
	            if (!Utils::check_img_type($_FILES['goods_img']['type']))
	            {
	                //sys_msg($_LANG['invalid_goods_img'], 1, array(), false);
	                $this->error("上传的商品图片无效");
	            }
	        }
	        elseif ($_FILES['goods_img']['error'] == 1)
	        {
	            //sys_msg(sprintf($_LANG['goods_img_too_big'], $php_maxsize), 1, array(), false);
	            $this->error("上传的商品图片太大");
	        }
	        elseif ($_FILES['goods_img']['error'] == 2)
	        {
	            //sys_msg(sprintf($_LANG['goods_img_too_big'], $htm_maxsize), 1, array(), false);
	            $this->error("上传的商品图片太大");
	        }
	
	        // 商品缩略图
	        if (isset($_FILES['goods_thumb']))
	        {
	            if ($_FILES['goods_thumb']['error'] == 0)
	            {
	                if (!Utils::check_img_type($_FILES['goods_thumb']['type']))
	                {
	                    //sys_msg($_LANG['invalid_goods_thumb'], 1, array(), false);
	                    $this->error("上传的商品压缩图片无效");
	                }
	            }
	            elseif ($_FILES['goods_thumb']['error'] == 1)
	            {
	                //sys_msg(sprintf($_LANG['goods_thumb_too_big'], $php_maxsize), 1, array(), false);
	                $this->error("上传的商品压缩图片太大");
	            }
	            elseif ($_FILES['goods_thumb']['error'] == 2)
	            {
	                //sys_msg(sprintf($_LANG['goods_thumb_too_big'], $htm_maxsize), 1, array(), false);
	                $this->error("上传的商品压缩图片太大");
	            }
	        }			
	        // 相册图片	        
	    }
		
	    /*处理图片*/
	    $goods_img        = '';  // 初始化商品图片
	    $goods_thumb      = '';  // 初始化商品缩略图
	    $original_img     = '';  // 初始化原始图片
	    $old_original_img = '';  // 初始化原始图片旧图
	    
		// 如果上传了商品图片,相应处理
	    if (($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none') or (($_POST['goods_img_url'] != $_LANG['lab_picture_url'] && $_POST['goods_img_url'] != 'http://') && $is_url_goods_img = 1)){
	    	if ($_REQUEST['goods_id'] > 0){
   	            /* 删除原来的图片文件 */
	            $sql = "SELECT goods_thumb, goods_img, original_img " .
	                    " FROM " . 'ybr_goods' .
	                    " WHERE goods_id = '$_REQUEST[goods_id]'";
	            //$row = $db->getRow($sql);
	            $row	=	M()->query($sql);
	            
	            if ($row['goods_thumb'] != '' && is_file($img_dir . $row['goods_thumb'])){
	                @unlink($img_dir . $row['goods_thumb']);
	            }
	            if ($row['goods_img'] != '' && is_file($img_dir . $row['goods_img'])){
	                @unlink($img_dir . $row['goods_img']);
	            }
	            if ($row['original_img'] != '' && is_file($img_dir . $row['original_img'])){
	                /* 先不处理，以防止程序中途出错停止 */
	                //$old_original_img = $row['original_img']; //记录旧图路径
	            }
	    	}
	    	
	    	
		    /* 是否自动生成缩略图  */
	    	if($_POST['auto_thumb'] ){	    		
	    		/* 上传原图,并且自动生成缩略图  */
			    $upload 			= 	new UploadFile();	// 实例化上传类
			    $upload->maxSize  	= 	3000000 ;			// 设置附件上传大小
			    $upload->allowExts  = 	array('jpg', 'gif', 'png', 'jpeg');	// 设置附件上传类型
			    $ymd              	=   date('Ymd');
			    $upload->savePath 	=  	'./Public/Upload/images/' . $ymd . '/';			// 设置附件上传目录
			    $upload->thumb 		= 	true;
			    $upload->thumbPrefix 	=	'thumb_';
				$upload->thumbMaxWidth 	= 	'300';		//设置缩略图最大宽度
				$upload->thumbMaxHeight = 	'300';		//设置缩略图最大高度
				
				$info				=	$upload->uploadOne($_FILES['goods_img'], $upload->savePath);		    
			    if($info){
			    	$goods_img		=	$ymd . '/' . $info[0]['savename'];
			    	$goods_thumb	=	$ymd . '/' . 'thumb_' . $info[0]['savename'];
			    }else{
			       $errorMsg		=	$upload->getErrorMsg();
			    }
	    	}
	    	else{
	    		// 上传商品图片
	    	 	$upload 			= 	new UploadFile();	// 实例化上传类
			    $upload->maxSize  	= 	3000000 ;			// 设置附件上传大小
			    $upload->allowExts  = 	array('jpg', 'gif', 'png', 'jpeg');	// 设置附件上传类型
			    $ymd              	=   date('Ymd');
			    $upload->savePath 	=  	'./Public/upload/images/' . $ymd . '/';			// 设置附件上传目录
				
				$info				=	$upload->uploadOne($_FILES['goods_img'], $upload->savePath);		    
			    if($info){
			    	//t($info);
			    	$goods_img		=	$ymd . '/' . $info[0]['savename'];
			    }else{
			       $errorMsg		=	$upload->getErrorMsg();
			    }
	    		
	    		// 上传缩略图
	    		$upload2 			= 	new UploadFile();	// 实例化上传类
			    $upload2->maxSize  	= 	3000000 ;			// 设置附件上传大小
			    $upload2->allowExts = 	array('jpg', 'gif', 'png', 'jpeg');	// 设置附件上传类型
			    $ymd              	=   date('Ymd');
			    $upload2->savePath 	=  	'./Public/upload/images/' . $ymd . '/';			// 设置附件上传目录
				
				$info				=	$upload2->uploadOne($_FILES['goods_thumb'], $upload2->savePath);		    
			    if($info){
			    	//t($info);
			    	$goods_thumb	=	$ymd . '/' . $info[0]['savename'];
			    }else{
			       $errorMsg				=	$upload->getErrorMsg();
			    }	    		
	    	}  	
	    }
	    
	 	/* 如果没有输入商品货号则自动生成一个商品货号 */
	    if (empty($_POST['goods_sn'])){
	        $max_id     		= 	"SELECT MAX(goods_id) + 1 FROM  ybr_goods";
	        $goods_sn   		= 	GoodsModel::generate_goods_sn($max_id);
	        $datas['goods_sn']	=	$goods_sn;    
	    }
	    else{
	        $goods_sn  		 	= 	$_POST['goods_sn'];
	        $datas['goods_sn']	=	$goods_sn;
	    }
	    
	    //echo "货号：" . $datas['goods_sn'] . '------';
	    
	    /*处理数据*/
	    $datas['goods_name']		=	$_POST['goods_name'];
	    $datas['shop_price']		=	!empty($_POST['shop_price']) ? $_POST['shop_price'] : 0;
	    $datas['market_price']		=	!empty($_POST['market_price']) ? $_POST['market_price'] : 0;
	    $datas['promote_price']		=	!empty($_POST['promote_price']) ? $_POST['promote_price'] : 0;
	    $datas['is_promote']		=	empty($_POST['promote_price']) ? 0 : 1;
	    $datas['integral']			=	empty($_POST['integral']) ? 0 : $_POST['integral'];
	    $datas['promote_start_date']=	($datas['is_promote'] && !empty($_POST['promote_start_date'])) ? Utils::local_strtotime($_POST['promote_start_date']) : 0;
	    $datas['promote_end_date']	=	($datas['is_promote'] && !empty($_POST['promote_end_date'])) ? Utils::local_strtotime($_POST['promote_end_date']) : 0;
	    $datas['goods_weight']		=	!empty($_POST['goods_weight']) ? $_POST['goods_weight'] * $_POST['weight_unit'] : 0;
	    $datas['is_best']			=	isset($_POST['is_best']) ? 1 : 0;
	    $datas['is_new']			=	isset($_POST['is_new']) ? 1 : 0;
	    $datas['is_hot']			=	isset($_POST['is_hot']) ? 1 : 0;
	    $datas['is_on_sale']		=	isset($_POST['is_on_sale']) ? 1 : 0;
	    $datas['is_alone_sale']		=	isset($_POST['is_alone_sale']) ? 1 : 0;
	    $datas['is_shipping']		=	isset($_POST['is_shipping']) ? $_POST['is_shipping'] : 0;
	    $datas['goods_number']		=	isset($_POST['goods_number']) ? $_POST['goods_number'] : 0;
	    $datas['warn_number']		=	isset($_POST['warn_number']) ? $_POST['warn_number'] : 0;
	    $datas['goods_type']		=	isset($_POST['goods_type']) ? $_POST['goods_type'] : 0;
	    $datas['give_integral']		=	isset($_POST['give_integral']) ? intval($_POST['give_integral']) : '-1';
	    $datas['rank_integral']		=	isset($_POST['rank_integral']) ? intval($_POST['rank_integral']) : '-1';
	    $datas['suppliers_id']		=	isset($_POST['suppliers_id']) ? intval($_POST['suppliers_id']) : '-1';	    
	    $datas['cat_id']			=	$_POST['cat_id'];
	    $datas['brand_id']			=	$_POST['brand_id'];
	    $datas['goods_brief']		=	$_POST['goods_brief'];
	    $datas['seller_note']		=	$_POST['seller_note'];
	    $datas['goods_desc']		=	$_POST['goods_desc'];
		// 商品图片
		if($goods_img != ''){
			$datas['goods_img']				=	$goods_img;
			$goods_datas['original_img']	=	$goods_img;
		}
		if($goods_thumb != ''){
			$datas['goods_thumb']		=	$goods_thumb == '' ? "" : $goods_thumb;		
		}
		
		// 关键字处理
		$keywords_arr 				= 	explode(" ", $_POST['keywords']);
        $keywords_arr 				= 	array_flip($keywords_arr);
        if (isset($keywords_arr[''])){
            unset($keywords_arr['']);
        }
        $datas['keywords']			=	join(' ', array_flip($keywords_arr));	
		        
        /* 如果有上传图片，删除原来的商品图 */
        $sql 						= 	"SELECT goods_thumb, goods_img, original_img " . " FROM " . ' ybr_goods ' . " WHERE goods_id = '$_REQUEST[goods_id]'";
        $row 						= 	$CommonModel->getRow($sql);
        
        //t($row);
        
        if ($goods_img && $row['goods_img'])
        {
            @unlink($img_dir . $row['goods_img']);
            @unlink($img_dir . $row['original_img']);
        }

        if ($goods_thumb && $row['goods_thumb'])
        {
            @unlink($img_dir . $row['goods_thumb']);
        }
		
        $goods_datas['goods_name']			=	$datas['goods_name'];
        $goods_datas['goods_name_style']	=	$datas['goods_name_style'];
        $goods_datas['goods_sn']			=	$datas['goods_sn'];
        $goods_datas['cat_id']				=	$datas['cat_id'];
        $goods_datas['brand_id']			=	$datas['brand_id'];
        $goods_datas['shop_price']			=	$datas['shop_price'];
        $goods_datas['market_price']		=	$datas['market_price'];
        $goods_datas['is_promote']			=	$datas['is_promote'];
        $goods_datas['promote_price']		=	$datas['promote_price'];
        $goods_datas['promote_start_date']	=	$datas['promote_start_date'];
        $goods_datas['suppliers_id']		=	$datas['suppliers_id'];
        $goods_datas['promote_end_date']	=	$datas['promote_end_date'];
        
        /* 如果有上传图片，需要更新数据库 */
        if ($goods_img){
            $goods_datas['goods_img']		=	$datas['goods_img'];
            $goods_datas['original_img']	=	$datas['original_img'];
        }
        if ($goods_thumb){
            $goods_datas['goods_thumb']	=	$datas['goods_thumb'];
        }
        if ($code != ''){
            $goods_datas['is_real']			=	0;
            $goods_datas['extension_code']	=	$code;
        }
        
         $goods_datas['keywords']		=	$datas['keywords'];
         $goods_datas['goods_brief']	=	$datas['goods_brief'];
         $goods_datas['seller_note']	=	$datas['seller_note'];
         $goods_datas['goods_weight']	=	$datas['goods_weight'];
         $goods_datas['goods_number']	=	$datas['goods_number'];
         $goods_datas['warn_number']	=	$datas['warn_number'];
         $goods_datas['integral']		=	$datas['integral'];
         $goods_datas['give_integral']	=	$datas['give_integral'];
         $goods_datas['rank_integral']	=	$datas['rank_integral'];
         $goods_datas['give_integral']	=	$datas['give_integral'];
         $goods_datas['is_best']		=	$datas['is_best'];
         $goods_datas['is_new']			=	$datas['is_new'];
         $goods_datas['is_hot']			=	$datas['is_hot'];
         $goods_datas['is_on_sale']		=	$datas['is_on_sale'];
         $goods_datas['is_alone_sale']	=	$datas['is_alone_sale'];
         $goods_datas['is_shipping']	=	$datas['is_shipping'];
         $goods_datas['goods_desc']		=	$datas['goods_desc'];
         $goods_datas['last_update']	=	gmtime();
         $goods_datas['goods_type']		=	$datas['goods_type'];
         $goods_datas['last_update']	=	$datas['last_update'];
		 
		 // // t($_POST);
		 // // t($goods_datas);
		 
		 
		 
		 
         /*更新数据*/        
       	 M("Goods")->where("goods_id='{$goods_id}'")->save($goods_datas);
       	
       	/*记录操作*/       	 
	    admin_log($_POST['goods_name'], 'edit', 'goods');
	    
	    /*处理图片相册*/
	    if((isset($_POST['img_id']) && isset($_POST['img_desc'])) || (empty($_POST['img_id']) && empty($_POST['img_desc']))){
	    	$img_id_list	=	$_POST['img_id'];
	    	$img_desc_list	=	$_POST['img_desc'];
	    	foreach($img_id_list as $k=>$img_id){
	    		$img_datas['goods_id']	=	$goods_id;
	    		$img_datas['img_desc']	=	$img_desc_list[$k];
	    		M('GoodsGallery')->where("img_id='{$img_id}'")->save($img_datas);
	    	}
	    }

    	/*处理属性 */
	    if ((isset($_POST['attr_id_list']) && isset($_POST['attr_value_list'])) || (empty($_POST['attr_id_list']) && empty($_POST['attr_value_list'])))
	    {
	        // 取得原有的属性值
	        $goods_attr_list 		= 	array();	
	        $keywords_arr		 	= 	explode(" ", $_POST['keywords']);	
	        $keywords_arr 			= 	array_flip($keywords_arr);
	        if (isset($keywords_arr[''])){
	            unset($keywords_arr['']);
	        }
	
	        $sql 					= 	"SELECT attr_id, attr_index FROM " . ' ybr_attribute ' . " WHERE cat_id = '{$_POST['goods_type']}'";	
	        $attr_res 				= 	M()->query($sql);	
	        $attr_list 				= 	array();
			
	        foreach($attr_res as $row){
	        	$attr_list[$row['attr_id']] 	= 	$row['attr_index'];
	        }
	
	        $sql 	= 	"SELECT g.*, a.attr_type FROM " . ' ybr_goods_attr ' . " AS g LEFT JOIN " . ' ybr_attribute ' . " AS a ON a.attr_id = g.attr_id WHERE g.goods_id = '$goods_id'";
			$res 	= 	M()->query($sql);
			
			foreach($res as $row){
				$goods_attr_list[$row['attr_id']][$row['attr_value']] 	= 	array('sign' => 'delete', 'goods_attr_id' => $row['goods_attr_id']);
			}
			
	        // 循环现有的，根据原有的做相应处理
	        if(isset($_POST['attr_id_list'])){
	            foreach ($_POST['attr_id_list'] AS $key => $attr_id){
	                $attr_value 	= 	$_POST['attr_value_list'][$key];
	                $attr_price 	= 	$_POST['attr_price_list'][$key];
	                if (!empty($attr_value)){
	                    if (isset($goods_attr_list[$attr_id][$attr_value])){
	                        // 如果原来有，标记为更新
	                        $goods_attr_list[$attr_id][$attr_value]['sign'] = 'update';
	                        $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
	                    }
	                    else
	                    {
	                        // 如果原来没有，标记为新增
	                        $goods_attr_list[$attr_id][$attr_value]['sign'] = 'insert';
	                        $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
	                    }
	                    $val_arr = explode(' ', $attr_value);
	                    foreach ($val_arr AS $k => $v)
	                    {
	                        if (!isset($keywords_arr[$v]) && $attr_list[$attr_id] == "1")
	                        {
	                            $keywords_arr[$v] = $v;
	                        }
	                    }
	                }
	            }
	        }
	        
	        $keywords 	= 	join(' ', array_flip($keywords_arr));
	
	        $sql 		= 	"UPDATE " . ' ybr_goods '. " SET keywords = '$keywords' WHERE goods_id = '$goods_id' LIMIT 1";	
	        M()->query($sql);
	
	        /* 插入、更新、删除数据 */
	        foreach ($goods_attr_list as $attr_id => $attr_value_list)
	        {
	            foreach ($attr_value_list as $attr_value => $info)
	            {
	                if ($info['sign'] == 'insert')
	                {
	                    $sql = "INSERT INTO " . ' ybr_goods_attr '. " (attr_id, goods_id, attr_value, attr_price)".
	                            "VALUES ('$attr_id', '$goods_id', '$attr_value', '$info[attr_price]')";
	                }
	                elseif ($info['sign'] == 'update')
	                {
	                    $sql = "UPDATE " . ' ybr_goods_attr ' . " SET attr_price = '$info[attr_price]' WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1";
	                }
	                else
	                {
	                    $sql = "DELETE FROM " . ' ybr_goods_attr '. " WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1";
	                }
	                M()->query($sql);
	            }
	        }
	    }
	
	    //t($_POST);
	    
	    /* 处理会员价格 */
	    if (isset($_POST['user_rank']) && isset($_POST['user_price']))
	    {
	        handle_member_price($goods_id, $_POST['user_rank'], $_POST['user_price']);
	    }
	
	    /* 处理优惠价格 */
	    if (isset($_POST['volume_number']) && isset($_POST['volume_price']))
	    {
	        $temp_num 	= 	array_count_values($_POST['volume_number']);
	        foreach($temp_num as $v)
	        {
	            if ($v > 1)
	            {
	                $this->error($GLOBALS['_LANG']['volume_number_continuous']);
	                break;
	            }
	        }
	        handle_volume_price($goods_id, $_POST['volume_number'], $_POST['volume_price']);
	    }
	
	    /* 处理扩展分类 */
	    if (isset($_POST['other_cat']))
	    {
	        handle_other_cat($goods_id, array_unique($_POST['other_cat']));
	    }
	    
	    /* 处理关联商品 */
        handle_link_goods($goods_id);
        /* 处理组合商品 */
        handle_group_goods($goods_id);
        /* 处理关联文章 */
        handle_goods_article($goods_id);
	    //U('goods/goods_list')
	    $this->success("操作成功");
	}
	
	// 商品回收站
	public function goods_trash(){
		
	}	
	
	// 商品批量修改
	public function mod_goods_batch(){
		
	}
	
	// 还原商品
	public function recover_goods(){
		
	}
	
	// 商品自动上下架
	public function goods_auto(){
		
	}
	
	// 虚拟商品列表
	public function vritual_goods_list(){}	
	// 添加虚拟商品
	public function add_virtual_goods(){}
	// 修改虚拟商品
	public function mod_virtual_goods(){}
	// 删除虚拟商品
	public function del_virtual_goods(){}
	
	
	/**
	 * 无刷新修改数据
	 * Enter description here ...
	 */
	public function ajax_goods(){
				
		$GoodsModel		=	M('Goods');
		
		$action			=	$_POST['action'];
		$field			=	$_POST['field'];
		$value			=	$_POST['value'];
		$goods_id		=	$_POST['id'];
		
		switch($action){
			case 'change':
				/* 修改的数据 */				
				$datas[$field]	=	$value == 1 ? 0 : 1;
				$GoodsModel->where("goods_id = '{$goods_id}'")->save($datas);
				$this->ajaxReturn($datas[$field],$datas[$field],1);
				break;
			case 'edit':
				/* 修改的数据 */
				$datas[$field]	=	$value;				
				$GoodsModel->where("goods_id = '{$goods_id}'")->save($datas);
				$this->ajaxReturn(1,$value,1);
				break;
			case 'del':
				break;			
			default:
				$this->ajaxReturn(0,'操作出错,请联系后台管理人员',1);
				break;
		}
	}
	
	
	
	
}
?>